#include "HighLight.h"

HighLight::HighLight (QTextDocument *parent)
    : QSyntaxHighlighter (parent)
{
    highlightingRules.clear ();
}

void HighLight::highlightBlock (const QString &text)
{
    qDebug () << "text content:" << text;
    IsFormats.clear ();
    foreach (HighlightingRule rule, highlightingRules)
    {
        QRegularExpression expression(rule.pattern);
        QRegularExpressionMatchIterator i = expression.globalMatch (text);
        while (i.hasNext ())
        {
            QRegularExpressionMatch match = i.next ();
            if (isContain (match.capturedStart (),match.capturedEnd ())) {
                qDebug () << "index content:" << match.capturedStart ();
                qDebug () << "lenght content:" << match.capturedLength ();
                setFormat (match.capturedStart (), match.capturedLength (), rule.format);
                FormatPosition j;
                j.startIndex = match.capturedStart ();
                j.endIndex = match.capturedStart ()+match.capturedLength ();
                IsFormats.append (j);
            }
        }
    }
}

void HighLight::setTextColor (const QString &str, const QColor &color)
{
    HighlightingRule rule;
    rule.pattern = str;
    QTextCharFormat format;
    format.setForeground (color);
    rule.format = format;
    highlightingRules.append (rule);
}

QVector<HighLight::HighlightingRule>& HighLight::getHighlightingRules()
{
    return highlightingRules;
}

bool HighLight::isContain(int startIndex,int endIndex)
{
    for (int i = 0; i < IsFormats.size (); ++i) {
        FormatPosition j = IsFormats.at (i);
        if (startIndex>= j.startIndex) {
            //在已经匹配到的范围内了
            if (endIndex <=j.endIndex) {
                return false;
            }
        }
    }
    return true;
}
